import json
import os
import threading
from typing import List

import requests
from fastapi import APIRouter

from app.schema import CallbackData
from global_config import *
from scripts import db_utils, image_utils
from scripts.beans import Storyboard

router = APIRouter()


@router.post("/onmessage")
def send_onmessage(body: CallbackData = None):
    if 'generating' == body.type:
        print(body.type, body.trigger_id, body.content)
    elif 'end' == body.type:
        workflow_path = f'{workflows_dir}{get_cur_project()}\\'
        storyboards_path = f'{workflow_path}{workflows_json}'

        def change(storyboards: List[Storyboard]):
            for v in storyboards:
                if v.trigger_id == body.trigger_id:
                    if body.attachments[0].url not in v.aiImgList:
                        v.aiImgList.append(body.attachments[0].url)
                    if body.attachments[0].filename not in v.aiImgNameList:
                        v.aiImgNameList.append(body.attachments[0].filename)

                # 创建线程
                if len(v.aiImgList) > 0 and len(v.aiImgNameList) > 0:
                    my_thread = threading.Thread(target=image_utils.save_mj_img, args=(v.aiImgList, v.aiImgNameList))
                    # 启动线程
                    my_thread.start()

            print(storyboards)

        if os.path.exists(storyboards_path):
            db_utils.modify_workflow(storyboards_path, change)


    return {"body": "ok"}
